package com.walkline.screen;

import localization.WeiboSDKResource;
import net.rim.blackberry.api.homescreen.HomeScreen;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.MainScreen;

import com.walkline.app.WeiboAppConfig;
import com.walkline.util.Enumerations.AppSource;
import com.walkline.util.Enumerations.RefreshRemindDelay;
import com.walkline.util.Enumerations.RepostCount;
import com.walkline.util.Enumerations.ShortcutKey;
import com.walkline.util.Enumerations.ShowStatusImage;
import com.walkline.util.Enumerations.StatusCount;
import com.walkline.util.Enumerations.StorageType;
import com.walkline.util.Enumerations.SuggestionCount;
import com.walkline.util.Enumerations.Themes;
import com.walkline.util.Function;
import com.walkline.util.container.ForegroundManager;
import com.walkline.util.container.RoundRectFieldManager;
import com.walkline.util.container.VerticalButtonFieldSet;
import com.walkline.weibo.WeiboAppConfigException;
import com.walkline.weibo.WeiboSDK;

public class ShowSettingsMainScreen extends MainScreen implements WeiboSDKResource
{
	private ForegroundManager _foreground;
	private CheckboxField checkboxAutoLogin;
	private CheckboxField checkboxOverwrite;
	//private CheckboxField checkboxAutoLoadStatusImages;
	private ObjectChoiceField choiceStatusCount;
	private ObjectChoiceField choiceRepostCount;
	private ObjectChoiceField choiceRemindDelay;
	private ObjectChoiceField choiceSuggestionCount;
	private ObjectChoiceField choiceStorage;
	private ObjectChoiceField choiceAutoLoadStatusImages;
	private ObjectChoiceField choiceShortcutKey;
	private ObjectChoiceField choiceAppSource;
	private ObjectChoiceField choiceThemes;
	private EditField editStorageLocation;

	private WeiboSDK _weibo;
	private WeiboAppConfig _appConfig;

	private static ResourceBundle _bundle = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);

	public ShowSettingsMainScreen(WeiboSDK weibo)
	{
		super(USE_ALL_HEIGHT | NO_VERTICAL_SCROLL | NO_SYSTEM_MENU_ITEMS);
		setTitle(getResString(SETTINGS_TITLE));

		_weibo = weibo;
		_appConfig = weibo.getAppConfig();

		RoundRectFieldManager managerLogin = new RoundRectFieldManager(true);
		RoundRectFieldManager managerList = new RoundRectFieldManager(true);
		RoundRectFieldManager managerRemind = new RoundRectFieldManager(true);
		RoundRectFieldManager managerImages = new RoundRectFieldManager(true);
		RoundRectFieldManager managerThemes = new RoundRectFieldManager(true);
		RoundRectFieldManager managerStorage = new RoundRectFieldManager(true);
		RoundRectFieldManager managerShortcutKey = new RoundRectFieldManager(true);
		RoundRectFieldManager managerAppSource = new RoundRectFieldManager(true);

		_foreground=new ForegroundManager(0);


		//Login option start
    	MyTitleLabelField labelLogin = new MyTitleLabelField(getResString(SETTINGS_LOGIN));

    	checkboxAutoLogin = new CheckboxField(getResString(SETTINGS_LOGIN_AUTOLOGIN), true, 134217728 | USE_ALL_WIDTH);
    	checkboxAutoLogin.setEnabled(false);

		MyDescriptionLabelField labelAutoLoginDescription = new MyDescriptionLabelField(getResString(SETTINGS_LOGIN_AUTOLOGIN_DESCRIPTION));

    	VerticalButtonFieldSet vbf = new VerticalButtonFieldSet(USE_ALL_WIDTH);
    	ButtonField buttonDeleteAccountInfo = new ButtonField(getResString(SETTINGS_LOGIN_BUTTON_CLEAN_INFORMATION), ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
    	buttonDeleteAccountInfo.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				cleanAccountInfo();
			}
		});
    	vbf.add(buttonDeleteAccountInfo);

    	managerLogin.add(labelLogin);
    	managerLogin.add(new SeparatorField());
    	managerLogin.add(checkboxAutoLogin);
    	managerLogin.add(labelAutoLoginDescription);
    	managerLogin.add(vbf);
		//Login option end


    	//List option start
    	MyTitleLabelField labelList = new MyTitleLabelField("列表");

    	String[] choicesStatusCount = StatusCount.choicesStatusCount;
    	String[] choicesRepostCount = RepostCount.choicesRepostCount;
    	String[] choicesSuggestion = SuggestionCount.choicesSuggestionCount;
    	choiceStatusCount = new ObjectChoiceField("微博/评论数量：", choicesStatusCount, StatusCount.DEFAULT_COUNT);
    	choiceRepostCount = new ObjectChoiceField("转发/评论数量：", choicesRepostCount, RepostCount.DEFAULT_COUNT);
    	choiceRepostCount.setEnabled(false);
    	choiceSuggestionCount = new ObjectChoiceField("搜索好友数量：", choicesSuggestion, SuggestionCount.DEFAULT_COUNT);
    	choiceSuggestionCount.setEnabled(false);

		MyDescriptionLabelField labelListDescription = new MyDescriptionLabelField("每次刷新列表显示的列表数量。");

    	managerList.add(labelList);
    	managerList.add(new SeparatorField());
    	managerList.add(choiceStatusCount);
    	managerList.add(choiceRepostCount);
    	managerList.add(choiceSuggestionCount);
    	managerList.add(labelListDescription);
    	//List option end


    	//Remind refresh delay option start
    	MyTitleLabelField labelRemindDelay = new MyTitleLabelField("消息提醒");

    	String[] choicesRemindDelay = RefreshRemindDelay.choicesRefreshDelay;
    	choiceRemindDelay = new ObjectChoiceField("刷新间隔：", choicesRemindDelay, RefreshRemindDelay.DEFAULT_DELAY);

		MyDescriptionLabelField labelRemindDelayDescription = new MyDescriptionLabelField("定时刷新消息提醒。");

    	managerRemind.add(labelRemindDelay);
    	managerRemind.add(new SeparatorField());
    	managerRemind.add(choiceRemindDelay);
    	managerRemind.add(labelRemindDelayDescription);
    	//Remind refresh delay option end


    	//Image option start
    	MyTitleLabelField labelImages = new MyTitleLabelField("图像");

    	String[] choicesAutoLoadStatusImages = ShowStatusImage.choicesShowStatusImage;
    	choiceAutoLoadStatusImages = new ObjectChoiceField("是否显示微博配图：", choicesAutoLoadStatusImages, ShowStatusImage.DEFAULT_OPTION);
    	//checkboxAutoLoadStatusImages = new CheckboxField("自动显示微博配图：", true, 134217728 | USE_ALL_WIDTH);

    	MyDescriptionLabelField labelAutoLoadStatusImageDescription = new MyDescriptionLabelField("设置刷新微博列表后微博配图显示方式。");

    	managerImages.add(labelImages);
    	managerImages.add(new SeparatorField());
    	managerImages.add(choiceAutoLoadStatusImages);
    	managerImages.add(labelAutoLoadStatusImageDescription);
    	//Image option end


    	//Themes option start
    	MyTitleLabelField labelTheme = new MyTitleLabelField("主题");

    	String[] choicesThemes = Themes.choicesThemes;
    	choiceThemes = new ObjectChoiceField("选择主题：", choicesThemes, choicesThemes);

    	MyDescriptionLabelField labelThemesDescription = new MyDescriptionLabelField("选择一个合适的主题配色。");

    	managerThemes.add(labelTheme);
    	managerThemes.add(new SeparatorField());
    	managerThemes.add(choiceThemes);
    	managerThemes.add(labelThemesDescription);
    	//Themes option end

    	//Storage option start
    	MyTitleLabelField labelStorage = new MyTitleLabelField(getResString(SETTINGS_STORAGE));

    	String[] choicesStorageLocation = getResStringArray(SETTINGS_STORAGE_LOCATION_ITEMS);
    	choiceStorage = new ObjectChoiceField(getResString(SETTINGS_STORAGE_LOCATION), choicesStorageLocation, StorageType.DEFAULT_TYPE) {
    		protected void fieldChangeNotify(int context)
    		{
				int selection = choiceStorage.getSelectedIndex();
				
				switch (selection)
				{
					case 0:
						editStorageLocation.setText(StorageType.choicesDownloadUri[StorageType.STORE]);
						break;
					case 1:
						editStorageLocation.setText(StorageType.choicesDownloadUri[StorageType.SDCARD]);
						break;
				}
				
				super.fieldChangeNotify(context);
    		};
		};

    	editStorageLocation = new EditField(getResString(SETTINGS_STORAGE_LOCATION_URI), StorageType.DEFAULT_URI, EditField.DEFAULT_MAXCHARS, EditField.READONLY | EditField.NO_NEWLINE | EditField.NON_SPELLCHECKABLE);

    	MyDescriptionLabelField labelStorageDescription = new MyDescriptionLabelField(getResString(SETTINGS_STORAGE_LOCATION_DESCRIPTION));

    	checkboxOverwrite = new CheckboxField(getResString(SETTINGS_STORAGE_OVERWRITE), true, 134217728 | USE_ALL_WIDTH);
    	checkboxOverwrite.setEnabled(false);

    	managerStorage.add(labelStorage);
    	managerStorage.add(new SeparatorField());
    	managerStorage.add(choiceStorage);
    	managerStorage.add(editStorageLocation);
    	managerStorage.add(labelStorageDescription);
    	managerStorage.add(checkboxOverwrite);
    	//Storage option end

    	//Shortcut key option start
    	MyTitleLabelField labelShortKey = new MyTitleLabelField(getResString(SETTINGS_SHORTCUT));

    	String[] choicesShortcutKeys = ShortcutKey.choicesShortcutKeys;
    	choicesShortcutKeys[0] = getResString(SETTINGS_SHORTCUT_NONE);
    	choiceShortcutKey = new ObjectChoiceField(getResString(SETTINGS_SHORTCUT_KEY), choicesShortcutKeys, ShortcutKey.DEFAULT_KEY);

    	MyDescriptionLabelField labelShortcutKeysDescription = new MyDescriptionLabelField(getResString(SETTINGS_SHORTCUT_KEY_DESCRIPTION));

    	managerShortcutKey.add(labelShortKey);
    	managerShortcutKey.add(new SeparatorField());
    	managerShortcutKey.add(choiceShortcutKey);
    	managerShortcutKey.add(labelShortcutKeysDescription);
    	//Shortcut key option end


    	//AppSource option start
    	MyTitleLabelField labelAppSource = new MyTitleLabelField("应用来源 (微博尾巴)");

    	String[] choicesAppSource = AppSource.choicesAppSource;    	
    	choiceAppSource = new ObjectChoiceField("选择一个来源：来自", choicesAppSource, AppSource.DEFAULT_SOURCE);

		MyDescriptionLabelField labelAppSourceDescription = new MyDescriptionLabelField("重要提示：更换应用来源后，必须重新登录你的账号！(工具菜单→重新登录)") {
			protected void paint(Graphics graphics)
			{
				graphics.setColor(Color.RED);
				super.paint(graphics);
			}
		};

    	managerAppSource.add(labelAppSource);
    	managerAppSource.add(new SeparatorField());
    	managerAppSource.add(choiceAppSource);
    	managerAppSource.add(labelAppSourceDescription);
		//AppSource option end

		_foreground.add(managerLogin);
		_foreground.add(managerList);
		_foreground.add(managerRemind);
		_foreground.add(managerImages);
		_foreground.add(managerStorage);
		_foreground.add(managerShortcutKey);
		_foreground.add(managerThemes);
		_foreground.add(managerAppSource);
		add(_foreground);

		loadData();
	}

	private String getResString(int key) {return _bundle.getString(key);}
	private String[] getResStringArray(int key) {return _bundle.getStringArray(key);}

	private void cleanAccountInfo()
	{
		_appConfig.setUsername("");
		_appConfig.setPassword("");
		_appConfig.save(null, false);

		Function.errorDialog(getResString(MESSAGE_INFO_CLEAN_ACCOUNT_SUCCESS));
	}

	private void loadData()
	{
		if (_appConfig != null)
		{
			checkboxAutoLogin.setChecked(_appConfig.isAutoMode());
			checkboxOverwrite.setChecked(_appConfig.isOverwrite());

			choiceAutoLoadStatusImages.setSelectedIndex(_appConfig.getAutoLoadImageMethod());
			choiceStatusCount.setSelectedIndex(_appConfig.getStatusCount());
			choiceRepostCount.setSelectedIndex(_appConfig.getRepostCount());
			choiceRemindDelay.setSelectedIndex(_appConfig.getRemindDelay());
			choiceSuggestionCount.setSelectedIndex(_appConfig.getSuggestionCount());
			choiceStorage.setSelectedIndex(_appConfig.getDownloadLocation());
			choiceThemes.setSelectedIndex(_appConfig.getThemes());
			choiceShortcutKey.setSelectedIndex(_appConfig.getShortcutKey());
			choiceAppSource.setSelectedIndex(_appConfig.getAppSource());
		} else{
			try {
				throw new WeiboAppConfigException(getResString(MESSAGE_ERROR_CANNOT_LOAD_SETTINGS));
			} catch (WeiboAppConfigException e) {Function.errorDialog(e.toString());}
		}	
	}

	private void saveData()
	{
		String newAppName = WeiboAppConfig.APP_TITLE;

		_appConfig.setAutoMode(checkboxAutoLogin.getChecked());
		_appConfig.setOverwrite(checkboxOverwrite.getChecked());

		_appConfig.setAutoLoadImageMethod(choiceAutoLoadStatusImages.getSelectedIndex());
		_appConfig.setStatusCount(choiceStatusCount.getSelectedIndex());
		_appConfig.setRepostCount(choiceRepostCount.getSelectedIndex());
		_appConfig.setRemindDelay(choiceRemindDelay.getSelectedIndex());
		_appConfig.setDownloadLocation(choiceStorage.getSelectedIndex());
		_appConfig.setSuggestionCount(choiceSuggestionCount.getSelectedIndex());
		_appConfig.setAppSource(choiceAppSource.getSelectedIndex());
		_appConfig.setThemes(choiceThemes.getSelectedIndex());
		_appConfig.setShortcutKey(choiceShortcutKey.getSelectedIndex());

		_appConfig.save(_weibo, true);

		if (_appConfig.getShortcutKey() > 0)
		{
			String shortcut_key = ShortcutKey.choicesShortcutKeys[_appConfig.getShortcutKey()];
			newAppName += "(" + shortcut_key + WeiboAppConfig.UNDERLINE + ")";
		}

		HomeScreen.setName(newAppName);
	}

	public boolean onSave()
	{
		saveData();
    	return true;
	}

	class MyTitleLabelField extends LabelField
	{
		public MyTitleLabelField(String text)
		{
			super(text, USE_ALL_WIDTH | LabelField.ELLIPSIS);

			setFont(WeiboAppConfig.FONT_SETTINGS_TITLE);
		}

		protected void paint(Graphics g)
		{
			g.setColor(Color.DARKGRAY);
			super.paint(g);	
		}
	}

	class MyDescriptionLabelField extends LabelField
	{
		public MyDescriptionLabelField(String text)
		{
			super(text);

			setFont(WeiboAppConfig.FONT_SETTINGS_DESCRIPTION);
		}
	}
}